﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;

// 地图管理(动态加载)
public class MapMgr
{
    // 一张背景的宽度
    private const float bgLength = 5.06f * 3;
    // 背景图循环
    private LoopMap _loopBG = new LoopMap();
    // 地图块循环
    private LoopMap _loopSceneBlock = new LoopMap();

    // 背景根节点
    GameObject _bgRoot;
    // 地图块根节点
    GameObject _mapRoot;
    SceneCamera _camera;

    private int _curMapBlockIndex = 0; // 列表内索引
    private List<int> _mapBlockIdList = new List<int>() { 1, 2 };

    public void Init(SceneCamera camera, GameObject mapRoot, GameObject bgRoot)
    {
        _mapRoot = mapRoot;
        _camera = camera;
        _bgRoot = bgRoot;

        _loopBG.Init(3);
        _loopSceneBlock.Init(2);

        loadSceneBlock();
    }

    public void CheckAndLoad()
    {
        checkAndLoadBG();
        checkAndLoadSceneBlock();
    }

    // 动态加载地图块
    private void checkAndLoadSceneBlock()
    {
        if (_loopSceneBlock.NextPos - 10 < _camera.transform.position.x)
        {
            loadSceneBlock();
        }
    }

    private void loadSceneBlock()
    {
        var obj = ResMgr.Instance.GetGameObject("SceneObj/SceneBlock/Block" + _mapBlockIdList[_curMapBlockIndex]);
        _curMapBlockIndex = ++_curMapBlockIndex % _mapBlockIdList.Count;

        obj.transform.SetParent(_mapRoot.transform, false);
        obj.transform.position += new Vector3(_loopSceneBlock.NextPos, 0, 0);
        SceneBlock block = obj.GetComponent<SceneBlock>();
        _loopSceneBlock.Add(obj, block.Length);
    }

    // 循环加载背景
    private void checkAndLoadBG()
    {
        var last = _loopBG.GetLast();
        if (last == null)
        {
            var bg = ResMgr.Instance.GetGameObject("SceneObj/BG/Background_BonusLevels_01_0");
            bg.transform.SetParent(_bgRoot.transform, false);
            bg.transform.position += new Vector3(_loopBG.NextPos, 0, 0);
            last = _loopBG.Add(bg, bgLength);
        }

        if (_loopBG.NextPos - 6 < _camera.transform.position.x)
        {
            var bg = ResMgr.Instance.GetGameObject("SceneObj/BG/Background_BonusLevels_01_0");
            bg.transform.SetParent(_bgRoot.transform, false);
            bg.transform.position += new Vector3(_loopBG.NextPos, 0, 0);
            _loopBG.Add(bg, bgLength);
        }
    }

}

